package com.chant.startFarming.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chant.startFarming.dto.LoginFormDTO;
import com.chant.startFarming.dto.Result;
import com.chant.startFarming.dto.UserDTO;
import com.chant.startFarming.entity.Users;
import com.chant.startFarming.mapper.UsersMapper;
import com.chant.startFarming.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chant.startFarming.utils.RedisUtils;
import com.chant.startFarming.utils.UserHolder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.chant.startFarming.utils.RedisConstants.LOGIN_USER_KEY;
import static com.chant.startFarming.utils.RedisConstants.LOGIN_USER_TTL;

/**
 * <p>
 * 用户表，存储系统用户的基本信息 服务实现类
 * </p>
 *
 * @author chant
 * @since 2025-03-31
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisUtils redisUtils;


    @Override
    public List<Users> searchUsers(String name, String phone, Integer role, Integer userStatus) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            queryWrapper.like("name", name);
        }
        if (phone != null && !phone.isEmpty()) {
            queryWrapper.like("phone", phone);
        }
        if (role != null) {
            queryWrapper.like("role", role);
        }
        if (userStatus != null) {
            queryWrapper.like("user_status", userStatus);
        }
        return this.list(queryWrapper);
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String username = loginForm.getUsername();
        String password = loginForm.getPassword();
        // 判断
        // 1.根据用户名查询用户
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Users user = this.getOne(queryWrapper);
        // 2.1检查用户是否存在
        if (user == null) {
            return Result.fail("用户不存在");
        }
        // 2.2.验证密码
        if (!password.equals(user.getPassword())) {
            return Result.fail("密码错误");
        }
        // 2.3.检查用户状态
        if (user.getUserStatus() == null || user.getUserStatus() == 0) {
            return Result.fail("用户未启用，无法登录");
        }

        // 3.随机生成 token，作为登录令牌
        String token = UUID.randomUUID().toString(true);

        // 4.1.将 UserDTO 对象转为 JSON 存储
        // 4.1.将 UserDTO 对象转为 JSON 存储
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setUsername(user.getUsername());
        userDTO.setName(user.getName());
        userDTO.setRole(user.getRole());
        userDTO.setUserStatus(user.getUserStatus());

        String userJson = null;
        try {
            userJson = objectMapper.writeValueAsString(userDTO);
        } catch (JsonProcessingException e) {
            return Result.fail("序列化失败");
        }

        // 4.2.存储
        String tokenKey = LOGIN_USER_KEY + token;
        boolean isSetSuccess = redisUtils.set(tokenKey, userDTO, LOGIN_USER_TTL, TimeUnit.MINUTES);
        if (!isSetSuccess) {
            return Result.fail("Redis存储失败");
        }

        // 5.将用户信息存储到ThreadLocal
        UserHolder.saveUser(userDTO);

        // 6. 返回token，以JSON格式
        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        result.put("role", String.valueOf(user.getRole()));

        // 7. 返回登录结果
        return Result.ok(result);
    }


}
